<?php

namespace Wanecho\Mobilelogin\Api\Controllers;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface as Response;
use Illuminate\Support\Arr;
use Wanecho\Mobilelogin\Api\WanechoSms;
use Flarum\User\User;
use Illuminate\Validation\Factory;

class ForgetpwdController implements RequestHandlerInterface
{
    protected $valid_period = 30 * 3; // sms timeout 3 minute
    protected $validator;

    public function __construct(
        Factory $validator
    ) {
        $this->validator = $validator;
    }
    public function handle(ServerRequestInterface $request): Response
    {
        $body = $request->getParsedBody();
        // $mobile = (int) Arr::get($body, 'mobile');
        $code = (int) Arr::get($body, 'code');
        // $password = Arr::get($body, 'pwd');
        $validator = $this->validator->make($body, [
            'mobile' => 'required',
            'code' => 'required|integer',
            'pwd' => 'required',
        ]);
        if ($validator->failed()) {
            return new JsonResponse($validator->errors()->first(), 500);
        }
        $sms_response = WanechoSms::where(['mobile' => $body['mobile'], 'is_active' => 0])->orderBy('id', 'desc')->first();
        if (!$sms_response) {
            return new JsonResponse('请先发送验证码', 500);
        }
        //检测验证码
        if ((int) $sms_response->code !== $code) {
            return new JsonResponse('短信验证码错误', 500);
        }
        $sms_response->is_active = 1;
        $sms_response->save();
        if ($sms_response->created_at > date('Y-m-d H:i:s', time() + $this->valid_period)) {
            return new JsonResponse('验证码已过期，请重新获取', 500);
        }
        $user = User::where(['mobile' => $body['mobile']])->first();
        $user->changePassword($body['pwd']);
        if ($user->save()) {
            return new JsonResponse('修改成功', 200);
        } else {
            return new JsonResponse('修改失败', 500);
        }
    }
}
